var express = require('express');
var feedbackRouter = express.Router();
const SQLQuery = require('../utils/query.js');


/**创建意见反馈接口
 * @param {name} 名称
 * @param {subject} 主题
 * @param {phone} 手机号
 * @param {message} 信息
 * */
feedbackRouter.post('/client/createFeedback', async function (req, res) {
  try {
    let queryObj = req.body;
    var addSql = 'insert into feedback(name,subject,phone,message,visitIP,createTime) values(?,?,?,?,?,?)';
    var addSqlParams = [queryObj.name, queryObj.subject, queryObj.phone, queryObj.message, req.headers['x-forwarded-for'] ? req.headers['x-forwarded-for'].split(',').pop().trim() : '0.0.0.0', new Date()];
    await SQLQuery.query(addSql, addSqlParams)
    res.send(global.common.resJson(0, 'success', null))
  } catch (err) {
    res.send(err)
  }
})


/**删除意见反馈接口
 * @param {id} 意见id
 * 
 * */
feedbackRouter.post('/deleteFeedback', async function (req, res) {

  try {
    let queryObj = req.body;
    let sql = "update feedback set isDeleted = 1 where id = ?";
    let result = await SQLQuery.query(sql, [queryObj.id]);
    if (result.affectedRows === 1) {
      res.send(global.common.resJson(0, '删除成功', null))
    } else {
      res.send(global.common.resJson(0, '已被删除', null))
    }
  } catch (err) {
    res.send(err)
  }
})


/**修改意见反馈接口
 * 
 * */
feedbackRouter.get('/updateFeedback', async function (req, res) {
  try {
    let queryObj = req.body;
    let sql = "update feedback set content = ? where id = ?";
    let result = await SQLQuery.query(sql, [queryObj.content, queryObj.id]);
    if (result.affectedRows === 1) {
      res.send(global.common.resJson(0, '修改成功', null))
    } else {
      res.send(global.common.resJson(0, '无修改内容', null))
    }
  } catch (err) {
    res.send(err)
  }
})


/**获取意见反馈列表接口
 * @param {searchStr} 模糊查询字符串
 * @param {pageSize} 页尺寸
 * @param {pageIndex} 页码
 * 
 * */
feedbackRouter.post('/feedbackList', async function (req, res) {

  try {
    let queryObj = req.body;
    let startNum = (queryObj.pageIndex - 1) * queryObj.pageSize;
    let sql = `SELECT id ,name,subject,phone,message,createTime FROM feedback WHERE CONCAT(name, ' ', message) LIKE '%${queryObj.searchStr}%' AND isDeleted = 0 LIMIT ${startNum},${queryObj.pageSize}`;
    let allsql = `SELECT * FROM feedback WHERE CONCAT(name, ' ', message) LIKE '%${queryObj.searchStr}%' AND isDeleted = 0`;
    let result = await SQLQuery.query(sql);
    let result2 = await SQLQuery.query(allsql);
    let data = {
      data: result,
      totalNum: result2.length
    }
    res.send(global.common.resJson(0, 'success!!', data));
  } catch (err) {
    res.send(err);
  }

})


module.exports = feedbackRouter;

